package com.glowworms.core.validator;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.glowworms.core.util.ObjectUtils;
import com.glowworms.core.validator.annotation.Validate;

/**
 * 
 */
public class AnnotationValidator implements Validator {
	
	/**
	 * 保护Validate注解的, 那么将会进行验证
	 */
	public boolean supports(Class<?> clazz) {
		Annotation annotation = clazz.getAnnotation(Validate.class); 
		return ObjectUtils.isNotNull(annotation);
	}

	/**
	 * 验证提交的数据类
	 */
	public void validate(Object target, Errors errors) {
		Field[] fields = target.getClass().getFields();
		for (Field field : fields) {
			field.setAccessible(true);
			Object fieldValue;
			String fieldName = field.getName();
			try {
				fieldValue = field.get(target);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			} 
			String errorMessage = doValidateField(field, fieldValue);
			if(ObjectUtils.isNotNull(errorMessage)){
				errors.reject(fieldName, null, errorMessage);
			}
		}
	}

	/**
	 * 逐个字段进行判断
	 * @param field
	 * @param fieldValue
	 */
	protected String doValidateField(Field field, Object fieldValue) {
		return null;
	}
}
